#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：10.在bs4中使用css选择器.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-11-27 10:30
'''
from bs4 import BeautifulSoup
import re

html = """
<html><head><title>The Dormouse's story1</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story2</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

soup = BeautifulSoup(html, 'lxml')

# 标签选择器
print("--------------标签选择器------------")
results = soup.select("title") # 专门使用css选择器语法完成标签定位
print(results)

results = soup.select("a")
print(results)

results = soup.select_one("a") # 查询符合条件的第一个标签
print(results)


# 类选择器：如果使用css选择器去基于class属性去筛选那么必须class属性前面加”.“
print("--------------类选择器------------")
results = soup.select(".sister")
print(results)

# id选择器：如果使用css选择器去基于id属性去筛选那么必须id属性前面加”#“
print("--------------id选择器------------")
results = soup.select("#link2")
print(results)


# 层级选择器：上级和下级用空格隔开，也可以复合使用
print("--------------层级选择器------------")
results = soup.select("p a")
print(results)
results = soup.select("p #link2")
print(results)
print("--------------属性选择器------------")
# 属性选择器：
results = soup.select("a[class=sister]")
print(results)

# 获取文本内容
print("--------------获取文本内容------------")
results = soup.select("title")[0].get_text()
print(results)
for temp in soup.select("title"):
    print(temp.getText())


for temp in soup.select("a"):
    print(temp.get('href'))
